import { ShoppingCart, ShoppingCartState } from "./component";
import { component } from "components/common/component";
import { BaseComponent } from "components/common/base-component";
import { asyncComponentState } from "common";
import React = require("react");
import * as ui from "maishu-ui-toolkit";


@component()
export class ShoppingCartFooter extends BaseComponent<any, Partial<ShoppingCartState>>{

    private _shoppingCart: ShoppingCart;

    constructor(props) {
        super(props);
        this.state = {};
    }

    get shoppingCart(): ShoppingCart {
        if (this._shoppingCart == null) {
            let c = this.masterPage.childComponents[ShoppingCart.name];
            console.assert(c.length == 1);
            this._shoppingCart = c[0] as ShoppingCart;
        }

        return this._shoppingCart;
    }

    checkAll(checked: boolean) {
        let { items } = this.state;
        console.assert(items != null);

        let status = this.state.status;
        if (status == "normal") {

            items.forEach(o => o.Selected = checked);
            this.setState({ items });
            return;
        }

        if (checked)
            this.setState({ editSelectedItems: items });
        else
            this.setState({ editSelectedItems: [] });
    }

    componentDidMount() {
        setTimeout(() => {
            // 必须要延时,才能获取到 shoppingCart 控件
            asyncComponentState(this.shoppingCart, this, "status", "editSelectedItems", "items");
        }, 100);
    }

    private selectedCount() {
        if (this.state.status == "normal") {
            let items = this.state.items || [];
            let count = 0;
            items.forEach(o => count + o.Count);

            return count;
        }

        return (this.state.editSelectedItems || []).length;
    }

    private isSelectedAll() {
        if (this.state.items.length == 0)
            return false;

        if (this.state.status == "normal") {
            let selectedItems = this.state.items.filter(o => o.Selected);
            return selectedItems.length == this.state.items.length && this.state.items.length > 0;
        }

        return this.state.editSelectedItems.length == this.state.items.length;
    }

    render() {
        if (this.state.editSelectedItems == null || this.state.items == null)
            return <></>

        let selectedCount = this.selectedCount();
        let isCheckedAll = this.isSelectedAll();

        let totalAmount = 0;
        this.state.items.forEach(o => {
            totalAmount = totalAmount + o.Amount * o.Count;
        });

        let { status } = this.state;

        return <div className="productInfoBottomBar-control shopping-shoppingCart">
            <div className="settlement" style={{ bottom: this.props.hideMenu ? 0 : null, paddingLeft: 0 }}>
                <div className="pull-right">
                    {status == 'normal' ?
                        <button className="btn btn-primary" disabled={selectedCount == 0}
                            ref={(e: HTMLButtonElement) => {
                                if (!e) return;
                                ui.buttonOnClick(e, () => this.shoppingCart.buy());
                            }}>
                            {selectedCount > 0 ? `结算（${selectedCount}）` : '结算'}
                        </button>
                        :
                        <button className="btn btn-primary" disabled={selectedCount == 0}
                            ref={(e: HTMLButtonElement) => {
                                if (!e) return;
                                ui.buttonOnClick(e, o => this.shoppingCart.removeSelectedItems(), {
                                    confirm: this.shoppingCart.removeConfirmText()
                                });
                            }}>
                            删除
                </button>
                    }
                </div>
                <div style={{ width: '100%', paddingTop: 8 }}>
                    <button className="select-all pull-left"
                        onClick={(e) => { this.checkAll(!this.isSelectedAll()) }}>
                        {isCheckedAll ?
                            <i className="icon-ok-sign text-primary"></i>
                            :
                            <i className="icon-circle-blank text-primary"></i>
                        }
                        <span className="text">全选</span>
                    </button>
                    {this.state.status == 'normal' ?
                        <label className="pull-right" style={{ paddingRight: 10, paddingTop: 2 }}>
                            总计：<span className="price">￥{totalAmount.toFixed(2)}</span>
                        </label>
                        : null
                    }
                </div>

            </div>
        </div>
    }
}